import { router } from ".";
import { Route, RouteObject } from "react-router-dom";

// 跳转到登录页面
export const toLoginPage = () => {
    router.navigate("/user/login");
};

// 按路径查找节点
function findNodeByPath(routes: RouteObject[], path: string) {
    // ??? TODO 为什么要 加1
    for (let k = 0; k < routes.length; k += 1) {
        const currentItem = routes[k];

        if (currentItem.path === path) return currentItem;

        findNodeByPath(currentItem.children || [], path);
    }
}

// 往 routes 中添加 路由
export const addRoutes = (parentPath: string, routes: RouteObject[]) => {
    if (!parentPath) {
        router.routes.push(...(routes as any));
        return;
    }

    const curNode = findNodeByPath(router.routes, parentPath);

    if (curNode?.children) {
        curNode?.children.push(...routes);
    } else if (curNode) {
        curNode.children = routes;
    }
};

export const replaceRoutes = (parentPath: string, routes: RouteObject) => {
    if (!parentPath) {
        router.routes.push(...(routes as any));
        return;
    }

    const curNode = findNodeByPath(router.routes, parentPath);

    if (curNode) {
        // ??? TODO 不能新增
        curNode.children = routes as any;
    }
};
